package com.lufan.controller;

import com.google.gson.Gson;
import com.lufan.data.vo.ApplyLoginQRCodeVo;
import com.lufan.data.vo.LoginInfoVo;
import com.lufan.data.vo.ScanQRCodeLoginVo;
import com.lufan.enums.ApiEnum;
import com.lufan.exception.CommonException;
import com.lufan.factory.HttpClientFactory;
import com.lufan.util.HttpUtil;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Objects;

@RestController
public class LoginController {

    private static final Gson gson = new Gson();
    private static String QR_CODE_KEY = "";

    /**
     * 申请二维码
     */
    @GetMapping("/apply")
    public ApplyLoginQRCodeVo applyLoginUrl() {
        OkHttpClient client = HttpClientFactory.getHttpClient();
        Response response = null;
        ApplyLoginQRCodeVo applyLoginQRCodeVo;
        try {
            response = HttpUtil.sendGet(client, ApiEnum.URL_APPLY.getUrl());
            if (response.isSuccessful() && response.body() != null) {
                String responseBody = response.body().string();
                applyLoginQRCodeVo = gson.fromJson(responseBody, ApplyLoginQRCodeVo.class);
                QR_CODE_KEY = applyLoginQRCodeVo.getQrCodeKey();
            } else {
                throw new CommonException("获取登录二维码失败，状态码: " + response.code());
            }
        } catch (IOException e) {
            throw new CommonException("获取登录二维码异常: " + e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return applyLoginQRCodeVo;
    }

    /**
     * 扫码登录
     */
    @GetMapping("/login")
    public ScanQRCodeLoginVo login() {
        OkHttpClient client = HttpClientFactory.getHttpClient();
        Response response = null;
        ScanQRCodeLoginVo scanQRCodeLoginVo = null;
        try {
            String query = String.format("?qrcode_key=%s", QR_CODE_KEY);
            String url = URI.create(ApiEnum.SCAN_QRCODE_LOGIN.getUrl() + query).toString();
            response = HttpUtil.sendGet(client, url);
            if (response.isSuccessful() && response.body() != null) {
                String responseBody = response.body().string();
                scanQRCodeLoginVo = gson.fromJson(responseBody, ScanQRCodeLoginVo.class);
                if (scanQRCodeLoginVo.getData().getCode() == 0 && scanQRCodeLoginVo.getCode() == 0 && scanQRCodeLoginVo.getData().getUrl() != null) {
                    List<Cookie> cookies = client.cookieJar().loadForRequest(Objects.requireNonNull(HttpUrl.parse(ApiEnum.SCAN_QRCODE_LOGIN.getUrl())));
                    for (Cookie cookie : cookies) {
                        if (cookie.name().equals("SESSDATA")) {
                            scanQRCodeLoginVo.setSessdata(cookie.value());
                            break;
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return scanQRCodeLoginVo;
    }

    /**
     * 查询用户登录信息
     */
    @GetMapping("/loginInfo")
    public LoginInfoVo loginInfo() {
        OkHttpClient client = HttpClientFactory.getHttpClient();
        Response response = null;
        LoginInfoVo loginInfoVo = null;
        try {
            response = HttpUtil.sendGet(client, ApiEnum.LOGIN_INFO.getUrl());
            if (response.isSuccessful() && response.body() != null) {
                String responseBody = response.body().string();
                loginInfoVo = gson.fromJson(responseBody, LoginInfoVo.class);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return loginInfoVo;
    }
}
